package logic

import (
	"context"
	"time"

	"mall/common/enumx"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateShowcaseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateShowcaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateShowcaseLogic {
	return &UpdateShowcaseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateShowcaseLogic) UpdateShowcase(in *forum.UpdateShowcaseReq) (*forum.UpdateShowcaseResp, error) {
	if in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	showcase := &model.ForumUserShowcase{
		UserID:      uint64(in.UserId),
		PlatformID:  uint(in.PlatformId),
		Background:  in.Background,
		Pattern:     in.Pattern,
		Frame:       in.Frame,
		Description: null.StringFrom(in.Desc),
		UpdatedAt:   time.Now(),
	}
	sid, err := l.svcCtx.ForumUser.UpdateShowcase(l.ctx, showcase, nil)
	if err != nil {
		return nil, err
	}

	mediaFilterMap := make(map[string]map[string][]interface{})
	mediaFilterMap[model.ForumAttachmentRelationshipColumns.ObjectID] = map[string][]interface{}{
		"equalTo": []interface{}{sid},
	}
	mediaFilterMap[model.ForumAttachmentRelationshipColumns.ObjectType] = map[string][]interface{}{
		"equalTo": []interface{}{enumx.ObjectTypeShowCase},
	}
	mediaList, _, listErr := l.svcCtx.ForumPost.GetMedia(l.ctx, model.M{}, -1, mediaFilterMap) // 读取关联表
	if listErr != nil {
		return nil, listErr
	}

	mediaMap := make(map[int64]*model.ForumAttachmentRelationship)
	mediaIdMap := make(map[int64]*model.ForumAttachmentRelationship)
	if len(mediaList) > 0 {
		for _, m := range mediaList {
			mediaMap[int64(m.AttachmentID)] = m
			mediaIdMap[int64(m.AttachmentRelationshipID)] = m
		}
	}

	extra := &model.ForumExtra{}
	if len(in.NewMedia) > 0 {
		for _, m := range in.NewMedia {
			if m.Id > 0 {
				var url string
				if m.Url != "" { // m.Uri attachment url当前版本  m.Url 最终版本
					url = m.Url
				} else {
					url = m.Uri
				}
				if m.Uid > 0 {
					if e, exist := mediaIdMap[m.Uid]; exist { // 已存在，修改
						delete(mediaMap, m.Id) // 排除掉不需要删除的项
						extra.Media = append(extra.Media, &model.ForumAttachmentRelationship{
							AttachmentRelationshipID: e.AttachmentRelationshipID,
							ObjectID:                 uint64(sid),
							ObjectType:               uint16(enumx.ObjectTypeShowCase),
							AttachmentOrder:          uint(m.Order),
							AttachmentImageURL:       url,
							AttachmentImageAlt:       m.AltText,
							AttachmentImageMeta:      m.Meta,
						})
					}
					continue
				}

				if e, exist := mediaMap[m.Id]; exist { // 已存在，修改
					delete(mediaMap, m.Id) // 排除掉不需要删除的项
					extra.Media = append(extra.Media, &model.ForumAttachmentRelationship{
						AttachmentRelationshipID: e.AttachmentRelationshipID,
						ObjectID:                 uint64(sid),
						ObjectType:               uint16(enumx.ObjectTypeShowCase),
						AttachmentOrder:          uint(m.Order),
						AttachmentImageURL:       url,
						AttachmentImageAlt:       m.AltText,
						AttachmentImageMeta:      m.Meta,
					})
					continue
				}

				extra.Media = append(extra.Media, &model.ForumAttachmentRelationship{
					ObjectID:            uint64(sid),
					ObjectType:          uint16(enumx.ObjectTypeShowCase),
					AttachmentID:        uint64(m.Id),
					AttachmentOrder:     uint(m.Order),
					AttachmentImageURL:  url,
					AttachmentImageAlt:  m.AltText,
					AttachmentImageMeta: m.Meta,
				})
			}
		}
	}
	for _, m := range mediaMap {
		extra.DelMediaIds = append(extra.DelMediaIds, m.AttachmentRelationshipID)
	}

	_, err = l.svcCtx.ForumUser.UpdateShowcase(l.ctx, nil, extra)
	if err != nil {
		return nil, err
	}

	return &forum.UpdateShowcaseResp{}, nil
}
